package cn.tsingmo.otproxy.security;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 解密处理器
 * 负责在数据进入管道时对其进行解密
 */
public class DecryptionHandler extends ChannelInboundHandlerAdapter {
    private static final Logger logger = LoggerFactory.getLogger(DecryptionHandler.class);
    private final EncryptionService encryptionService;

    /**
     * 构造函数
     * @param encryptionService 加密服务实例
     */
    public DecryptionHandler(EncryptionService encryptionService) {
        this.encryptionService = encryptionService;
    }

    /**
     * 读取数据并解密
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (!(msg instanceof ByteBuf)) {
            logger.error("接收到非ByteBuf类型的消息");
            ctx.close();
            return;
        }

        try {
            // 从ByteBuf中读取字节数据
            ByteBuf byteBuf = (ByteBuf) msg;
            byte[] encryptedData = new byte[byteBuf.readableBytes()];
            byteBuf.readBytes(encryptedData);
            byteBuf.release(); // 释放ByteBuf资源

            // 解密数据
            byte[] decryptedData = encryptionService.decrypt(encryptedData);

            // 将解密后的数据传递给下一个处理器
            ctx.fireChannelRead(decryptedData);
        } catch (Exception e) {
            logger.error("数据解密失败", e);
            ctx.close(); // 解密失败时关闭连接
        }
    }

    /**
     * 异常处理
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.error("解密处理器异常", cause);
        ctx.close();
    }
}